package com.example.mymusicplayer;

import static com.example.mymusicplayer.AlbumContents.TheAlbum;
import static com.example.mymusicplayer.MainActivity.musicFiles;
import static com.example.mymusicplayer.MainActivity.randomBoolean;
import static com.example.mymusicplayer.MainActivity.repeatBoolean;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.palette.graphics.Palette;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Random;

public class Media_page extends AppCompatActivity implements MediaPlayer.OnCompletionListener{
private ImageView BackArrow,TopMenu,Random,repeat,NextMusic,PerMusic,CoverView,TheBackGround;
private FloatingActionButton Start;
private SeekBar  seekBar;
private TextView DurationTime,TotalTime,ArtistName_TheMedia,MusicName_TheMedia;
static ArrayList<MusicFiles> listSongs = new ArrayList<>();

    @Override
    public void onCompletion(MediaPlayer mp) {
        NextBtnClicked();
        if(mediaPlayer!=null){
            mediaPlayer=MediaPlayer.create(getApplicationContext(),uri);
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(this);
        }
    }

    int position = -1;
static Uri uri;
static MediaPlayer mediaPlayer;
private Handler handler =new Handler();
private Thread playThread,prevThread,nextThread;

    @Override
    protected void onResume() {
        super.onResume();
        playThreadBtn();
        nextThreadBtn();
        prevThreadBtn();
    }

    private void prevThreadBtn() {
        prevThread=new Thread(){
            @Override
            public void run() {
                super.run();
                PerMusic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PreBtnClicked();
                    }


                });
            }
        };
        prevThread.start();
    }

    private void PreBtnClicked() {
        if(mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.release();
            if(randomBoolean&&!repeatBoolean){
                position=getRandom(listSongs.size()-1);
            }
            if(!repeatBoolean&&!randomBoolean){
                position=(position-1)%listSongs.size();
            }
            if(position<0)
                position=listSongs.size()-1;
            uri=Uri.parse(listSongs.get(position).getPath());
            mediaPlayer=MediaPlayer.create(getApplicationContext(),uri);
            metaData(uri);
            MusicName_TheMedia.setText(listSongs.get(position).getTitle());
            ArtistName_TheMedia.setText(listSongs.get(position).getArtist());
            seekBar.setMax(mediaPlayer.getDuration()/1000);
            Media_page.this.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    if(mediaPlayer!=null){
                        int mCurrentPosition = mediaPlayer.getCurrentPosition()/1000;
                        seekBar.setProgress(mCurrentPosition);
                    }
                }
            });
            mediaPlayer.setOnCompletionListener(this);
            Start.setBackgroundResource(R.drawable.ic_baseline_pause_24);
            mediaPlayer.start();

        }
        else {
            mediaPlayer.stop();
            mediaPlayer.release();
            if(randomBoolean&&!repeatBoolean){
                position=getRandom(listSongs.size()-1);
            }
            if(!repeatBoolean&&!randomBoolean){
                position=(position-1)%listSongs.size();
            }
            if(position<0)
                position=listSongs.size()-1;
            uri=Uri.parse(listSongs.get(position).getPath());
            mediaPlayer=MediaPlayer.create(getApplicationContext(),uri);
            metaData(uri);
            MusicName_TheMedia.setText(listSongs.get(position).getTitle());
            ArtistName_TheMedia.setText(listSongs.get(position).getArtist());
            seekBar.setMax(mediaPlayer.getDuration()/1000);
            Media_page.this.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    if(mediaPlayer!=null){
                        int mCurrentPosition = mediaPlayer.getCurrentPosition()/1000;
                        seekBar.setProgress(mCurrentPosition);
                    }
                }
            });
            mediaPlayer.setOnCompletionListener(this);
            Start.setBackgroundResource(R.drawable.ic_baseline_play_arrow_24);
        }
    }

    private void nextThreadBtn() {
        nextThread=new Thread(){
            @Override
            public void run() {
                super.run();
                NextMusic.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        NextBtnClicked();
                    }


                });
            }
        };
        nextThread.start();
    }

    private void  NextBtnClicked() {
        Log.e("Bollean","The Random is "+randomBoolean);
        Log.e("Bollean","The Shuffle is "+repeatBoolean);
        if(mediaPlayer.isPlaying()){
            mediaPlayer.stop();
            mediaPlayer.release();
            if(randomBoolean&&!repeatBoolean){
                position=getRandom(listSongs.size()-1);
            }
           else if(!repeatBoolean){
                position=(position+1)%listSongs.size();
            }
            uri=Uri.parse(listSongs.get(position).getPath());
            mediaPlayer=MediaPlayer.create(getApplicationContext(),uri);
            metaData(uri);
            MusicName_TheMedia.setText(listSongs.get(position).getTitle());
            ArtistName_TheMedia.setText(listSongs.get(position).getArtist());
            seekBar.setMax(mediaPlayer.getDuration()/1000);
            Media_page.this.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    if(mediaPlayer!=null){
                        int mCurrentPosition = mediaPlayer.getCurrentPosition()/1000;
                        seekBar.setProgress(mCurrentPosition);
                    }
                }
            });

            Start.setBackgroundResource(R.drawable.ic_baseline_pause_24);
            mediaPlayer.start();

        }
        else {
            mediaPlayer.stop();
            mediaPlayer.release();
            if(randomBoolean&&!repeatBoolean){
                position=getRandom(listSongs.size()-1);
            }
            else if(!repeatBoolean){
                position=(position+1)%listSongs.size();
            }
            uri=Uri.parse(listSongs.get(position).getPath());
            mediaPlayer=MediaPlayer.create(getApplicationContext(),uri);
            metaData(uri);
            MusicName_TheMedia.setText(listSongs.get(position).getTitle());
            ArtistName_TheMedia.setText(listSongs.get(position).getArtist());
            seekBar.setMax(mediaPlayer.getDuration()/1000);
            Media_page.this.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    if(mediaPlayer!=null){
                        int mCurrentPosition = mediaPlayer.getCurrentPosition()/1000;
                        seekBar.setProgress(mCurrentPosition);
                    }
                }
            });
            Start.setBackgroundResource(R.drawable.ic_baseline_play_arrow_24);
        }
    }

    private int getRandom(int i) {
        Random random = new Random();
        return random.nextInt(i+1);
    }

    private void playThreadBtn() {
        playThread=new Thread(){
            @Override
            public void run() {
                super.run();
                Start.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        playPauseBtnClicked();
                    }


                });
                Random.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        Log.e("Bollean","Before The Random is "+randomBoolean);
                        if(randomBoolean){
                            randomBoolean=false;
                            Random.setImageResource(R.drawable.shuffle_24);
                            Log.e("Bollean","After The Random is "+randomBoolean);
                        }
                        else{
                            randomBoolean=true;
                            Random.setImageResource(R.drawable.ic_baseline_shuffle_24_on);

                            Log.e("Bollean","After The Random is "+randomBoolean);
                        }
                    }
                });
                repeat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(repeatBoolean){
                            repeatBoolean=false;
                            repeat.setImageResource(R.drawable.repeat_off);

                        }
                        else{
                            repeatBoolean=true;
                            repeat.setImageResource(R.drawable.repeat);
                        }
                    }
                });
            }
};
        playThread.start();
    }
    private void playPauseBtnClicked() {
        if(mediaPlayer.isPlaying()){
            Start.setImageResource(R.drawable.ic_baseline_play_arrow_24);
            mediaPlayer.pause();
            seekBar.setMax(mediaPlayer.getDuration()/1000);
            Media_page.this.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    if(mediaPlayer!=null){
                        int mCurrentPosition = mediaPlayer.getCurrentPosition()/1000;
                        seekBar.setProgress(mCurrentPosition);
                    }
                }
            });
        }
        else
        {
            Start.setImageResource(R.drawable.ic_baseline_pause_24);
            mediaPlayer.start();
            seekBar.setMax(mediaPlayer.getDuration()/1000);
        }
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.media_page);
        InitAll();
        getInterMethod();
        MusicName_TheMedia.setText(listSongs.get(position).getTitle());
        ArtistName_TheMedia.setText(listSongs.get(position).getArtist());
        mediaPlayer.setOnCompletionListener(this);
            Media_page.this.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    if(mediaPlayer!=null){
                        int mCurrentPosition = mediaPlayer.getCurrentPosition()/1000;
                        seekBar.setProgress(mCurrentPosition);
                        DurationTime.setText(formattedTime(mCurrentPosition));

                    }
                    handler.postDelayed(this,1000);
                }
            });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(mediaPlayer!=null&&b){
                    mediaPlayer.seekTo(i*1000);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private String formattedTime(int mCurrentPosition) {
        String totalout ="";
        String totalNew ="";
        String seconds = String.valueOf(mCurrentPosition%60);
        String minutes = String .valueOf(mCurrentPosition/60);
        totalout = minutes+":"+seconds;
        totalNew = minutes+":"+"0"+seconds;
        if(seconds.length()==1){
            return totalNew;
        }
        else return totalout;
    }

    private void getInterMethod() {
        Intent intent = getIntent();
        position=getIntent().getIntExtra("position",-1);
        String msg = intent.getStringExtra("TheMsg");
        if(msg!=null && msg.equals("FromAlbum")){
            listSongs=TheAlbum;
        }
        else {
        listSongs = musicFiles;}
        if(listSongs !=null){
            Start.setImageResource(R.drawable.ic_baseline_pause_24);
            uri = Uri.parse(listSongs.get(position).getPath());
        }
        if(mediaPlayer!=null){

            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
            mediaPlayer.start();
        }
        else{
            mediaPlayer = MediaPlayer.create(getApplicationContext(),uri);
            mediaPlayer.start();
        }
        seekBar.setMax(mediaPlayer.getDuration()/1000);
        metaData(uri);
    }
    private void metaData(Uri uri){
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(uri.toString());
        int durationTotal = Integer.parseInt(listSongs.get(position).getDuration())/1000;
        TotalTime.setText(formattedTime(durationTotal));
        byte[] art = retriever.getEmbeddedPicture();
        Bitmap bitmap;
        if(art!=null){
            bitmap= BitmapFactory.decodeByteArray(art,0, art.length);
            AnimationForView(this,CoverView,bitmap);
            Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
                @Override
                public void onGenerated(@Nullable Palette palette) {
                    Palette.Swatch swatch = palette.getDominantSwatch();
                    if(swatch!=null){
                        ImageView gredient = findViewById(R.id.TheBackGround);
                        LinearLayout TheMainLayout = findViewById(R.id.TheMainLayout);
                        gredient.setBackgroundResource(R.drawable.gradient);
                        TheMainLayout.setBackgroundResource(R.drawable.background);
                        GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP,new int[]{swatch.getRgb(),0x00000000});
                        gredient.setBackground(gradientDrawable);
                        GradientDrawable gradientDrawableBg = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP,new int[]{swatch.getRgb(),swatch.getRgb()});
                        TheMainLayout.setBackground(gradientDrawableBg);
                        MusicName_TheMedia.setTextColor(swatch.getTitleTextColor());
                        ArtistName_TheMedia.setTextColor(swatch.getBodyTextColor());
                    }
                    else{
                        ImageView gredient = findViewById(R.id.TheBackGround);
                        LinearLayout TheMainLayout = findViewById(R.id.TheMainLayout);
                        gredient.setBackgroundResource(R.drawable.gradient);
                        TheMainLayout.setBackgroundResource(R.drawable.background);
                        GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP,new int[]{0xff000000,0x00000000});
                        gredient.setBackground(gradientDrawable);
                        GradientDrawable gradientDrawableBg = new GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP,new int[]{0xff000000,0xff000000});
                        TheMainLayout.setBackground(gradientDrawableBg);
                        MusicName_TheMedia.setTextColor(Color.WHITE);
                        ArtistName_TheMedia.setTextColor(Color.DKGRAY);
                    }
                }
            });
        }
        else

        {   bitmap= BitmapFactory.decodeByteArray(art,0, art.length);
            AnimationForView(this,CoverView,bitmap);
            ImageView gredient = findViewById(R.id.coverArt);
            LinearLayout TheMainLayout = findViewById(R.id.TheMainLayout);
            gredient.setBackgroundResource(R.drawable.gradient);
            TheMainLayout.setBackgroundResource(R.drawable.background);
            MusicName_TheMedia.setTextColor(Color.WHITE);
            ArtistName_TheMedia.setTextColor(Color.DKGRAY);
        }
    }
        public void AnimationForView(Context context,ImageView imageview,Bitmap bitmap){
            Animation out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);
            Animation In = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
         //   Glide.with(context).load(bitmap).into(imageview);
            out.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    Glide.with(context).load(bitmap).into(imageview);
                    In.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });

                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            imageview.startAnimation(out);
    }
    private void InitAll(){
        BackArrow = findViewById(R.id.BackArrow);
        TopMenu=findViewById(R.id.TopMenu);
        Random=findViewById(R.id.Random);
        repeat=findViewById(R.id.repeat);
        NextMusic=findViewById(R.id.NextMusic);
        PerMusic=findViewById(R.id.PerMusic);
        Start=findViewById(R.id.Start);
        seekBar = findViewById(R.id.seekBar);
        DurationTime = findViewById(R.id.DurationTime);
        TotalTime = findViewById(R.id.TotalTime);
        CoverView  = findViewById(R.id.coverArt);
        ArtistName_TheMedia=findViewById(R.id.ArtistName_TheMedia);
        MusicName_TheMedia=findViewById(R.id.MusicName_TheMedia);
        NextMusic = findViewById(R.id.NextMusic);
        PerMusic=findViewById(R.id.PerMusic);
        TheBackGround=findViewById(R.id.TheBackGround);
        Random = findViewById(R.id.Random);
        repeat = findViewById(R.id.repeat);

    }
}